package com.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.test.DbUtilsTest;


import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBPoolUtils {

    //数据源只需要创建一次就好了
    private static DataSource ds = null;

    //单例模式
    private DBPoolUtils() {}

    /**
     * 通过单例获取DataSource数据源
     * @return
     */
    public static DataSource getDataSource() {
        if (ds == null) {
            synchronized (DBPoolUtils.class) {
                if (ds == null) {
                    try {
                        ds = DruidDataSourceFactory.createDataSource(getProperties("db.properties"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return ds;
    }

    //返回连接
    public static Connection getConnection() {
        try {
            return ds == null?null:ds.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取Properties的对象
     * @param propertiesName Properties文件名包括src下的路径
     * @return 这个文件的Properties对象
     */
    private static Properties getProperties(String propertiesName){
        //通过反射获取编译路径的根目录并拼接文件相对路径
        String path = DbUtilsTest.class.getResource("/").getPath() + propertiesName;
        try {
            //将中文和符合转码
            path = URLDecoder.decode(path, "UTF-8");
            //创建Properties对象
            Properties p = new Properties();
            //创建输入流
            p.load(new FileInputStream(path));
            //返回
            return p;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }





}
